# -*- coding:utf-8 -*-
"""
@author:ym
@time:06-2020/6/28-
"""

import requests
import re
import execjs
from lxml import html
import traceback
import time
import sys, os
if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
# import fix_qt_import_error
from PyQt5.QtWidgets import QApplication, QMainWindow, QDesktopWidget
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer
from urllib import parse


class Logger:
    def __init__(self):
        self.file = "logger.log"
        try:
            with open(self.file, "r", encoding="UTF-8") as f:
                f.close()
        except:
            with open(self.file, "w+", encoding="UTF-8") as f:
                f.close()

    def write(self, mes):
        with open(self.file, "a+", encoding="UTF-8") as f:
            mes = str(self.__get_time()) + "：" + str(mes) + "\n\n\n"
            f.writelines(mes)
            # 测试使用
            print(mes)

    def __get_time(self):
        return time.strftime('%m-%d-%H:%M:%S ', time.localtime(time.time()))


class School:
    """
    __init__: usre  password  登录使用的账号密码
    get_js ： 调用js来加密得到信息
    login_in： 登录，成功返回true
    """

    def __init__(self, user, password):
        self.ses = requests.session()
        self.user = user
        self.password = password
        self.logger = Logger()
        self.name = ''
        self.cookies = ""

    def __get_js(self, msg):  # python 调用JS加密 返回 加密后的结果
        with open('conwork.js', encoding='utf-8') as f:
            js = execjs.compile(f.read())
            return js.call('encodeInp', msg)

    def __get_login_cookies(self):
        header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0",
            "Upgrade-Insecure-Requests": "1",
            "Connection": "keep-alive",
            "Host": "jwgl.hutb.edu.cn"
        }
        url = "http://jwgl.hutb.edu.cn/jsxsd/"
        try:
            stat = self.ses.get(url=url, headers=header, timeout=1000).status_code
            if stat != 200:
                mes = "教务系统进入失败！:School->81"
                # print(mes)
                return None
            # self.ses.cookies = stat.
            cookies = self.ses.cookies.get_dict()  # 获得临时的cookies
            cookies = str(cookies).replace("{", '').replace("'", '').replace(":", '=').replace('}', '').replace(",",
                                                                                                                ";")
            cookies = cookies.replace("= ", "=")
            self.cookies = cookies
            return cookies

        except:
            # print(mes)
            self.logger.write("教务系统进入抛出错误！:School->97")
            return None

    def __login(self, cookies, jsmsg):
        # 让COOkies 生效
        header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded",  # 接收类型
            "Host": "jwgl.hutb.edu.cn",
            "Referer": "http://jwgl.hutb.edu.cn/jsxsd/",
            "Upgrade-Insecure-Requests": "1",
            "Origin": "http://jwgl.hutb.edu.cn",
            "Proxy-Connection": "keep-alive",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0",
        }
        PostData = {
            'encoded': jsmsg  # 账号密码加密后的东西
        }
        url = 'http://jwgl.hutb.edu.cn/jsxsd/xk/LoginToXk'
        try:
            # 让Cookies 通过验证
            msg = self.ses.post(url, headers=header, data=PostData, timeout=1000)
            # print(msg.)
            if (msg.status_code != 200):
                msg = "登录页面失败！School->126"
                self.logger.write(msg)
                return False
            tree = html.fromstring(msg.text)
            # 查看是否有提示密码错误
            error = tree.xpath("//font[@color='red']/text()")
            if len(error) > 0:
                if str(error[0]) == "用户名或密码错误":
                    msg = "用户名或密码错误!"
                    self.logger.write(msg)
                    return False
            return True
        except Exception as e:
            msg = "登录抛出异常!:137"
            self.logger.write(msg)
            self.logger.write(traceback.format_exc())
            return False

    def __verification(self):
        # 验证是否正常成功，返回自己的姓名
        name = None
        try:
            url = "http://jwgl.hutb.edu.cn/jsxsd/framework/xsMain.jsp"
            response = self.ses.get(url=url).text
            # 姓名和学号的 xpath： /html/body/div[5]/div/div[3]
            tree = html.fromstring(response)
            user = tree.xpath("/html/body/div[5]/div/div[3]/text()")
            name = str(user[0]).replace("\n", "").replace("\t", "").replace("姓名：", "").replace(" ", "")
        except Exception as e:
            self.logger.write("School->153:登录验证失败")
            self.logger.write(str(traceback.format_exc()))
        return name

    def login_in(self):
        # 输入账号密码，让cookies 生效
        # 加密
        jsmsg = str(self.__get_js(self.user)) + "%%%" + str(self.__get_js(self.password)) + "="
        if self.__get_login_cookies():  # cookies 初始化
            if self.__login(self.user, jsmsg):
                # print("登录成功!")
                self.name = self.__verification()
                return True
            else:
                # print("登录失败！")
                return False
        else:
            return False

    def get_qk_page1(self):
        #  教务系统显示的那个无用链接
        url = "http://jwgl.hutb.edu.cn/jsxsd/xsxk/xklc_view?jx0502zbid=0B78EA08934C47148576964D6A532F4D"
        response = self.ses.get(url=url)
        print(response.status_code)
        print(response.text)

    def get_qk_page2(self):
        "/jsxsd/xsxk/xsxk_index?jx0502zbid="
        url = "http://jwgl.hutb.edu.cn/jsxsd/xsxk/xsxk_index?jx0502zbid=0B78EA08934C47148576964D6A532F4D"
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "max-age=0",
            "Cookie": self.cookies,
            "Host": "jwgl.hutb.edu.cn",
            "Proxy-Connection": "keep-alive",
            "Referer": "http://jwgl.hutb.edu.cn/jsxsd/xsxk/xklc_view?jx0502zbid=0B78EA08934C47148576964D6A532F4D",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0",
        }
        try:
            response = self.ses.get(url=url, headers=headers)
            # print(response.text)

            if response.status_code != 200:
                self.logger.write("School->199:抢课进入失败!")
                return False
            # print(response.text)
            if "<title>学生选课</title>" in str(response.text):
                return True
            else:
                return False
        except Exception as e:
            #  因为系统可能会关闭，可能会抛出错误
            # self.logger.write("School->177:登录验证失败")
            # self.logger.write(str(traceback.format_exc()))
            return False

    def findClassByOne(self, kcName, kcTeacher, kcWeek, kcJC):
        """
            :param kcName: 课程名字
            :param kcTeacher: 老师
            :param kcWeek: 上课星期
            :param kcJC: 上课节次
            :return: 字典型
            注意URL的汉字需要转urlencode,要转两次，
        """
        # 转码2次
        kcTeacher = parse.quote(parse.quote(str(kcTeacher)))
        kcName = parse.quote(parse.quote(str(kcName)))
        jxid = ""
        url = "http://jwgl.hutb.edu.cn/jsxsd/xsxkkc/xsxkGgxxkxk?kcxx=" + str(
            kcName) + "&skls=" + str(kcTeacher) + "&skxq=" + str(kcWeek) + "&skjc=" + str(
            kcJC) + "&sfym=false&sfct=true&szjylb=&sfxx=true"
        # url = "http://jwgl.hutb.edu.cn/jsxsd/xsxkkc/xsxkGgxxkxk?kcxx=%2509%25E7%25BE%258E%25E5%25AD%25A6%25E4%25B8%258E%25E6%25AC%25A3%25E8%25B5%258FX&skls=%25E5%25B8%2588%25E8%258A%25B3&skxq=2&skjc=11-12-&sfym=false&sfct=true&szjylb=&sfxx=true"

        data = {
            "sEcho": "1",
            "iColumns": "16",
            "sColumns": "",
            "iDisplayStart": "0",
            "iDisplayLength": "15",
            "mDataProp_0": "kch",
            "mDataProp_1": "kcmc",
            "mDataProp_2": "kcsx",
            "mDataProp_3": "zxs",
            "mDataProp_4": "ktmc",
            "mDataProp_5": "xxrs",
            "mDataProp_6": "syrs",
            "mDataProp_7": "xf",
            "mDataProp_8": "skls",
            "mDataProp_9": "sksj",
            "mDataProp_10": "skdd",
            "mDataProp_11": "xqmc",
            "mDataProp_12": "xkrs",
            "mDataProp_13": "ctsm",
            "mDataProp_14": "szkcflmc",
            "mDataProp_15": "czOper"
        }
        head1 = {
            "Host": "jwgl.hutb.edu.cn",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0",
            "Accept": "*/*",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate",
            "Referer": "http://jwgl.hutb.edu.cn/jsxsd/xsxkkc/comeInGgxxkxk",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "X-Requested-With": "XMLHttpRequest",
            "Connection": "keep-alive",
            "Cookie": self.cookies,
            "Pragma": "no-cache",
            "Cache-Control": "no-cache",
        }
        try:
            response = requests.post(url=url, data=data, headers=head1)
            if response.status_code != 200:
                self.logger.write("请求异常")
                return {"code": 100, "msg": "请求异常！"}
            msg = response.json()
            try:
                # 没有抛出异常那就有问题
                if str(msg["flag1"]) == str(2):
                    # print(msg)
                    # print("请先登录系统")
                    return {"code": 100, "msg": "请先登录教务系统！"}
            except:
                pass
            try:
                addData = msg["aaData"]
                # 如果是空的，直接返回
                if not addData:
                    return {"code": 100, "msg": "找不到该课程请检查课程、老师以及上课时间！"}
                for i in addData:
                    jxid = i["jx0404id"]
                if jxid:
                    return {"code": 200, "msg": "添加成功！", "jxid": str(jxid)}
            except:
                return {"code": 400, "msg": "出现错误School->292"}
                self.logger.write(str(traceback.format_exc()))

        except:
            return {"code": 400, "msg": "出现错误School->296"}
            self.logger.write(str(traceback.format_exc()))

    def findClassByAll(self, kcName):
        # 转码2次
        kcName = parse.quote(parse.quote(str(kcName)))
        jxid = ""
        url = "http://jwgl.hutb.edu.cn/jsxsd/xsxkkc/xsxkGgxxkxk?kcxx=" + str(
            kcName) + "&skls=&skxq=&skjc=&sfym=false&sfct=true&szjylb=&sfxx=true"
        # url = "http://jwgl.hutb.edu.cn/jsxsd/xsxkkc/xsxkGgxxkxk?kcxx=%2509%25E7%25BE%258E%25E5%25AD%25A6%25E4%25B8%258E%25E6%25AC%25A3%25E8%25B5%258FX&skls=%25E5%25B8%2588%25E8%258A%25B3&skxq=2&skjc=11-12-&sfym=false&sfct=true&szjylb=&sfxx=true"

        data = {
            "sEcho": "1",
            "iColumns": "16",
            "sColumns": "",
            "iDisplayStart": "0",
            "iDisplayLength": "15",
            "mDataProp_0": "kch",
            "mDataProp_1": "kcmc",
            "mDataProp_2": "kcsx",
            "mDataProp_3": "zxs",
            "mDataProp_4": "ktmc",
            "mDataProp_5": "xxrs",
            "mDataProp_6": "syrs",
            "mDataProp_7": "xf",
            "mDataProp_8": "skls",
            "mDataProp_9": "sksj",
            "mDataProp_10": "skdd",
            "mDataProp_11": "xqmc",
            "mDataProp_12": "xkrs",
            "mDataProp_13": "ctsm",
            "mDataProp_14": "szkcflmc",
            "mDataProp_15": "czOper"
        }
        head1 = {
            "Host": "jwgl.hutb.edu.cn",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0",
            "Accept": "*/*",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate",
            "Referer": "http://jwgl.hutb.edu.cn/jsxsd/xsxkkc/comeInGgxxkxk",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "X-Requested-With": "XMLHttpRequest",
            "Connection": "keep-alive",
            "Cookie": self.cookies,
            "Pragma": "no-cache",
            "Cache-Control": "no-cache",
        }
        try:
            response = requests.post(url=url, data=data, headers=head1)
            if response.status_code != 200:
                self.logger.write("教务系统未开放")

                return {"code": 100, "msg": "教务系统未开放！"}
            msg = response.json()
            try:
                # 没有抛出异常那就有问题
                if str(msg["flag1"]) == str(2):
                    # print(msg)
                    # print("请先登录系统")
                    return {"code": 100, "msg": "请先登录教务系统！"}
            except:
                pass
            try:
                addData = msg["aaData"]
                # 如果是空的，直接返回
                if not addData:
                    return {"code": 100, "msg": "找不到该课程请检查课程、老师以及上课时间！"}
                jxid = []
                for i in addData:
                    jxid.append(i["jx0404id"])
                if jxid:
                    return {"code": 200, "msg": "添加成功！", "jxid": jxid}
            except:
                return {"code": 400, "msg": "出现错误School->372"}
                self.logger.write(str(traceback.format_exc()))

        except:
            return {"code": 400, "msg": "出现错误School->295"}
            self.logger.write(str(traceback.format_exc()))

    def findClassByTYPE(self, type):
        url = "http://jwgl.hutb.edu.cn/jsxsd/xsxkkc/xsxkGgxxkxk?kcxx=&skls=&skxq=&skjc=&sfym=false&sfct=true&szjylb=" + str(
            type) + "&sfxx=true"
        data = {
            "sEcho": "1",
            "iColumns": "16",
            "sColumns": "",
            "iDisplayStart": "0",
            "iDisplayLength": "15",
            "mDataProp_0": "kch",
            "mDataProp_1": "kcmc",
            "mDataProp_2": "kcsx",
            "mDataProp_3": "zxs",
            "mDataProp_4": "ktmc",
            "mDataProp_5": "xxrs",
            "mDataProp_6": "syrs",
            "mDataProp_7": "xf",
            "mDataProp_8": "skls",
            "mDataProp_9": "sksj",
            "mDataProp_10": "skdd",
            "mDataProp_11": "xqmc",
            "mDataProp_12": "xkrs",
            "mDataProp_13": "ctsm",
            "mDataProp_14": "szkcflmc",
            "mDataProp_15": "czOper"
        }
        head1 = {
            "Host": "jwgl.hutb.edu.cn",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0",
            "Accept": "*/*",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate",
            "Referer": "http://jwgl.hutb.edu.cn/jsxsd/xsxkkc/comeInGgxxkxk",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "X-Requested-With": "XMLHttpRequest",
            "Connection": "keep-alive",
            "Cookie": self.cookies,
            "Pragma": "no-cache",
            "Cache-Control": "no-cache",
        }
        try:
            response = requests.post(url=url, data=data, headers=head1)
            if response.status_code != 200:
                self.logger.write("请求异常")
                return {"code": 100, "msg": "请求异常！"}
            msg = response.json()
            try:
                # 没有抛出异常那就有问题
                if str(msg["flag1"]) == str(2):
                    # print(msg)
                    # print("请先登录系统")
                    return {"code": 100, "msg": "请先登录教务系统！"}
            except:
                pass
            try:
                addData = msg["aaData"]
                # 如果是空的，直接返回
                if not addData:
                    return {"code": 100, "msg": "找不到该课程请检查课程、老师以及上课时间！"}
                jxid = []
                for i in addData:
                    jxid.append(i["jx0404id"])
                if jxid:
                    return {"code": 200, "msg": "添加成功！", "jxid": jxid}
            except:
                return {"code": 400, "msg": "出现错误School->372"}
                self.logger.write(str(traceback.format_exc()))

        except:
            return {"code": 400, "msg": "出现错误School->295"}
            self.logger.write(str(traceback.format_exc()))

    def post_Class(self, id):
        """
        :param id: 课程的ID
        :return:字典型，如果code 是100 说明是状态错误，400说明本次抢课失败
        """
        url = "http://jwgl.hutb.edu.cn/jsxsd/xsxkkc/ggxxkxkOper?jx0404id=" + str(id) + "&xkzy=&trjf="
        header = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0",
            'Referer': 'http://172.30.1.70/srun_portal_pc.php?ac_id=1',
        }
        try:
            response = self.ses.get(url=url)
            if response.status_code != 200:
                return {"code": 100}
            msg = response.json()
            try:
                if msg["success"]:
                    # 抢课成功
                    return {"code": 200, "msg": "抢课成功！"}
                elif not msg["success"]:
                    message = msg["message"]
                    if message == "选课失败：当前教学班已选择！":
                        return {"code": 200, "msg": "抢课成功！"}
                    return {"code": 400, "msg": str(msg["message"])}
                else:
                    return {"code": 100, "msg": str(msg["message"])}
            except:
                return {"code": 100}
        except:
            self.logger.write("school->310::")
            self.logger.write(str(traceback.format_exc()))
            return {"code": 100}
        """
        #  Cookie 唯一，最好不要在多个地方登录
        返回的类型：
        下面两个状态需要发挥异常，重新登录
        404
        请登录
        {"flag1":2,"msgContent":"请先登录系统"}
        选课失败
        {"success":false,"message":"选课失败：当前课程往年已选择！"}
        # 选课失败
        {"success":false,"message":"选课失败：此课堂选课人数已满！"}

        # 选课失败，
        {"success":false,"message":"选课失败：系统设定了当前全校公共选修课选课学分不能超过2学分！"}

        # 选课成功
        {"jfViewStr":"","success":true}
        # 选课失败，当前已经选则，就是抢课成功
        {"success":false,"message":"选课失败：当前教学班已选择！"}
        """

    def restart(self, deep):
        #  并没有使用
        # 如果登录成功
        # 最多递归10次
        if deep > 10:
            return False
        if (self.login_in()):
            return True
        else:
            return self.restart(deep + 1)

    def is_ready(self):
        """
         是否准许进入抢课网页
        :return: Bool
        """
        return self.get_qk_page2()


class Ui_MainWindow(QtWidgets.QMainWindow):
    def setupUi(self, MainWindow):
        # 人工部分
        # 记录目前任务的数量
        self.count = 0
        # 是否登录，登录为True
        self.flag = False
        # 是否能抢课
        self.QKflag = False
        # 抢课的唯一标识符
        self.QKID = 0
        # 需要抢课的列表
        self.QKall = {}
        # 根据名字抢课的列表

        self.QKNAME = []
        # 根据类型抢课的列表
        self.QKTYPE = []
        # 是否成功
        self.SUCCESS = {}
        # 日志类
        self.logger = Logger()
        # School类 ，保存的是用户信息
        self.USER = None

        #  自动生成部分
        MainWindow.setWindowIcon(QIcon('icon.png'))
        MainWindow.setObjectName("可爱多百宝箱1.0")
        MainWindow.setFixedSize(1146, 821)
        MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.Button = QtWidgets.QPushButton(self.centralwidget)
        self.Button.setGeometry(QtCore.QRect(350, 310, 91, 51))
        self.Button.setObjectName("Button")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(360, 20, 471, 81))
        self.label_2.setStyleSheet("font: 26pt \"Adobe Arabic\";")
        self.label_2.setTextFormat(QtCore.Qt.AutoText)
        self.label_2.setObjectName("label_2")
        self.notChangeLable4 = QtWidgets.QLabel(self.centralwidget)
        self.notChangeLable4.setGeometry(QtCore.QRect(840, 420, 271, 21))
        self.notChangeLable4.setScaledContents(False)
        self.notChangeLable4.setWordWrap(True)
        self.notChangeLable4.setTextInteractionFlags(
            QtCore.Qt.LinksAccessibleByMouse | QtCore.Qt.TextSelectableByKeyboard | QtCore.Qt.TextSelectableByMouse)
        self.notChangeLable4.setObjectName("notChangeLable4")
        self.user1Frame = QtWidgets.QFrame(self.centralwidget)
        self.user1Frame.setGeometry(QtCore.QRect(0, 360, 771, 401))
        self.user1Frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.user1Frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.user1Frame.setObjectName("user1Frame")
        self.notChangeLable1 = QtWidgets.QLabel(self.user1Frame)
        self.notChangeLable1.setGeometry(QtCore.QRect(210, 0, 251, 51))
        self.notChangeLable1.setObjectName("notChangeLable1")
        self.layoutWidget = QtWidgets.QWidget(self.user1Frame)
        self.layoutWidget.setGeometry(QtCore.QRect(60, 60, 701, 17))
        self.layoutWidget.setObjectName("layoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_6 = QtWidgets.QLabel(self.layoutWidget)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout.addWidget(self.label_6)
        self.label_9 = QtWidgets.QLabel(self.layoutWidget)
        self.label_9.setObjectName("label_9")
        self.horizontalLayout.addWidget(self.label_9)
        self.label_8 = QtWidgets.QLabel(self.layoutWidget)
        self.label_8.setObjectName("label_8")
        self.horizontalLayout.addWidget(self.label_8)
        self.notChangeLable6 = QtWidgets.QLabel(self.centralwidget)
        self.notChangeLable6.setGeometry(QtCore.QRect(870, 480, 251, 231))
        self.notChangeLable6.setText("")
        self.notChangeLable6.setPixmap(QtGui.QPixmap("flower.png"))
        self.notChangeLable6.setScaledContents(True)
        self.notChangeLable6.setObjectName("notChangeLable6")
        self.notChangeLable3 = QtWidgets.QLabel(self.centralwidget)
        self.notChangeLable3.setGeometry(QtCore.QRect(760, 100, 361, 261))
        self.notChangeLable3.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
        self.notChangeLable3.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.notChangeLable3.setScaledContents(False)
        self.notChangeLable3.setObjectName("notChangeLable3")
        self.notChangeLable5 = QtWidgets.QLabel(self.centralwidget)
        self.notChangeLable5.setGeometry(QtCore.QRect(830, 440, 261, 41))
        self.notChangeLable5.setObjectName("notChangeLable5")
        self.notChangeLable2 = QtWidgets.QLabel(self.centralwidget)
        self.notChangeLable2.setGeometry(QtCore.QRect(860, 70, 111, 31))
        self.notChangeLable2.setStyleSheet("font: 12pt \"Adobe Arabic\";")
        self.notChangeLable2.setObjectName("notChangeLable2")
        self.splitter_7 = QtWidgets.QSplitter(self.centralwidget)
        self.splitter_7.setGeometry(QtCore.QRect(490, 100, 137, 15))
        self.splitter_7.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_7.setObjectName("splitter_7")
        self.label_3 = QtWidgets.QLabel(self.splitter_7)
        self.label_3.setObjectName("label_3")
        self.hnucLable = QtWidgets.QLabel(self.splitter_7)
        self.hnucLable.setObjectName("hnucLable")
        self.splitter_6 = QtWidgets.QSplitter(self.centralwidget)
        self.splitter_6.setGeometry(QtCore.QRect(310, 100, 107, 17))
        self.splitter_6.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_6.setObjectName("splitter_6")
        self.label = QtWidgets.QLabel(self.splitter_6)
        self.label.setObjectName("label")
        self.baiduLable = QtWidgets.QLabel(self.splitter_6)
        self.baiduLable.setFrameShadow(QtWidgets.QFrame.Plain)
        self.baiduLable.setObjectName("baiduLable")
        self.label_10 = QtWidgets.QLabel(self.centralwidget)
        self.label_10.setGeometry(QtCore.QRect(110, 190, 131, 16))
        self.label_10.setObjectName("label_10")
        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setGeometry(QtCore.QRect(600, 370, 511, 20))
        self.label_7.setObjectName("label_7")
        self.splitter_8 = QtWidgets.QSplitter(self.centralwidget)
        self.splitter_8.setGeometry(QtCore.QRect(50, 210, 270, 24))
        self.splitter_8.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_8.setObjectName("splitter_8")
        self.IDLable_2 = QtWidgets.QLabel(self.splitter_8)
        self.IDLable_2.setObjectName("IDLable_2")
        self.kcNameLineEdit = QtWidgets.QLineEdit(self.splitter_8)
        self.kcNameLineEdit.setEchoMode(QtWidgets.QLineEdit.Normal)
        self.kcNameLineEdit.setObjectName("kcNameLineEdit")
        self.splitter_10 = QtWidgets.QSplitter(self.centralwidget)
        self.splitter_10.setGeometry(QtCore.QRect(80, 240, 239, 24))
        self.splitter_10.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_10.setObjectName("splitter_10")
        self.label_11 = QtWidgets.QLabel(self.splitter_10)
        self.label_11.setObjectName("label_11")
        self.kcTeacherLineEdit = QtWidgets.QLineEdit(self.splitter_10)
        self.kcTeacherLineEdit.setEchoMode(QtWidgets.QLineEdit.Normal)
        self.kcTeacherLineEdit.setObjectName("kcTeacherLineEdit")
        self.splitter_2 = QtWidgets.QSplitter(self.centralwidget)
        self.splitter_2.setGeometry(QtCore.QRect(-10, 300, 330, 24))
        self.splitter_2.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_2.setObjectName("splitter_2")
        self.IDLable_3 = QtWidgets.QLabel(self.splitter_2)
        self.IDLable_3.setObjectName("IDLable_3")
        self.kcWeekLineEdit = QtWidgets.QLineEdit(self.splitter_2)
        self.kcWeekLineEdit.setText("")
        self.kcWeekLineEdit.setEchoMode(QtWidgets.QLineEdit.Normal)
        self.kcWeekLineEdit.setObjectName("kcWeekLineEdit")
        self.splitter_11 = QtWidgets.QSplitter(self.centralwidget)
        self.splitter_11.setGeometry(QtCore.QRect(-10, 270, 330, 24))
        self.splitter_11.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_11.setObjectName("splitter_11")
        self.IDLable_4 = QtWidgets.QLabel(self.splitter_11)
        self.IDLable_4.setObjectName("IDLable_4")
        self.kcJCLineEdit = QtWidgets.QLineEdit(self.splitter_11)
        self.kcJCLineEdit.setEchoMode(QtWidgets.QLineEdit.Normal)
        self.kcJCLineEdit.setObjectName("kcJCLineEdit")
        self.splitter_9 = QtWidgets.QSplitter(self.centralwidget)
        self.splitter_9.setGeometry(QtCore.QRect(380, 270, 337, 24))
        self.splitter_9.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_9.setObjectName("splitter_9")
        self.label_13 = QtWidgets.QLabel(self.splitter_9)
        self.label_13.setObjectName("label_13")
        self.NewkcNameLineEdit = QtWidgets.QLineEdit(self.splitter_9)
        self.NewkcNameLineEdit.setEchoMode(QtWidgets.QLineEdit.Normal)
        self.NewkcNameLineEdit.setObjectName("NewkcNameLineEdit")
        self.splitter_12 = QtWidgets.QSplitter(self.centralwidget)
        self.splitter_12.setGeometry(QtCore.QRect(380, 240, 337, 24))
        self.splitter_12.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_12.setObjectName("splitter_12")
        self.label_12 = QtWidgets.QLabel(self.splitter_12)
        self.label_12.setObjectName("label_12")
        self.NewkcTypeLineEdit = QtWidgets.QLineEdit(self.splitter_12)
        self.NewkcTypeLineEdit.setEchoMode(QtWidgets.QLineEdit.Normal)
        self.NewkcTypeLineEdit.setObjectName("NewkcTypeLineEdit")
        self.splitter_5 = QtWidgets.QSplitter(self.centralwidget)
        self.splitter_5.setGeometry(QtCore.QRect(490, 210, 224, 24))
        self.splitter_5.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_5.setObjectName("splitter_5")
        self.nickLable = QtWidgets.QLabel(self.splitter_5)
        self.nickLable.setObjectName("nickLable")
        self.nickLineEdit = QtWidgets.QLineEdit(self.splitter_5)
        self.nickLineEdit.setObjectName("nickLineEdit")
        self.splitter_3 = QtWidgets.QSplitter(self.centralwidget)
        self.splitter_3.setGeometry(QtCore.QRect(120, 150, 631, 28))
        self.splitter_3.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_3.setObjectName("splitter_3")
        self.splitter = QtWidgets.QSplitter(self.splitter_3)
        self.splitter.setOrientation(QtCore.Qt.Horizontal)
        self.splitter.setObjectName("splitter")
        self.userLable = QtWidgets.QLabel(self.splitter)
        self.userLable.setObjectName("userLable")
        self.userLineEdit = QtWidgets.QLineEdit(self.splitter)
        self.userLineEdit.setObjectName("userLineEdit")
        self.userPasswordLable = QtWidgets.QLabel(self.splitter_3)
        self.userPasswordLable.setObjectName("userPasswordLable")
        self.passwordLineEdit = QtWidgets.QLineEdit(self.splitter_3)
        self.passwordLineEdit.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.passwordLineEdit.setEchoMode(QtWidgets.QLineEdit.Password)
        self.passwordLineEdit.setObjectName("passwordLineEdit")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1147, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "未开的一朵花"))
        self.Button.setText(_translate("MainWindow", "确认"))
        self.label_2.setText(_translate("MainWindow", "欢迎使用可爱多工具1.0"))
        self.notChangeLable4.setText(_translate("MainWindow", "取次花丛懒回顾，半缘修道半缘君"))
        self.notChangeLable1.setText(
            _translate("MainWindow", "<html><head/><body><p align=\"center\">用户：NULL</p></body></html>"))
        self.label_6.setText(_translate("MainWindow", "正在进行的任务"))
        self.label_9.setText(_translate("MainWindow", "状态"))
        self.label_8.setText(_translate("MainWindow", "操作"))
        self.notChangeLable3.setText(_translate("MainWindow",
                                                "<html><head/><body><p>1、每次只能选择一门课加入抢课任务</p><p>（只需要登录一次）<span style=\" color:#ff0000;\">一次最多进行8个任务</span>。</p><p>2、<span style=\" color:#ff0000;\">每次必须输入备注</span>，如果抢扩容，按照要求全部填上</p><p>如果准备新增课或者抢某一类新增课程，只需要填右边选一填。</p><p>3、状态会显示是否抢课成功。</p><p>4、有问题请反馈<span style=\" color:#ff0000;\">QQ：1021644865</span></p><p>5、请勿大范围传播，否则将收回软件。</p><p>6、作者：ym。</p><p>7、源码和使用地址</p></body></html>"))
        self.notChangeLable5.setText(_translate("MainWindow", "花开堪折直须折，莫待无花空折枝"))
        self.notChangeLable2.setText(_translate("MainWindow", "使用说明"))
        self.label_3.setText(_translate("MainWindow", "教务系统状态："))
        self.hnucLable.setText(_translate("MainWindow", "<html><head/><body><p>null</p></body></html>"))
        self.label.setText(_translate("MainWindow", "网络状态："))
        self.baiduLable.setText(_translate("MainWindow", "<html><head/><body><p>null</p></body></html>"))
        self.label_10.setText(_translate("MainWindow",
                                         "<html><head/><body><p align=\"center\"><span style=\" font-size:10pt;\">扩容抢课必填</span></p></body></html>"))
        self.label_7.setText(_translate("MainWindow", "https://gitee.com/ym_0101/HutbEduAdminSystem"))
        self.IDLable_2.setText(_translate("MainWindow", "   课程名字："))
        self.label_11.setText(_translate("MainWindow", "上课老师:"))
        self.IDLable_3.setText(_translate("MainWindow", "   上课时间（星期）："))
        self.IDLable_4.setText(_translate("MainWindow", "   上课时间（节次）："))
        self.label_13.setText(_translate("MainWindow", "(新增自动抢)名字类型："))
        self.label_12.setText(_translate("MainWindow", "(新增自动抢)课程类型："))
        self.nickLable.setText(_translate("MainWindow", "*备注："))
        self.userLable.setText(_translate("MainWindow", "教务系统账号:"))
        self.userPasswordLable.setText(_translate("MainWindow", "教务系统密码:"))

        # 可以被鼠标选择
        self.notChangeLable3.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse)
        self.label_7.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse)
        # 人工调试部分

        # 绑定任务
        self.binding()
        # 网络监察部分
        self.test_network()

    def binding(self):
        # 所有事件绑定和开始状态检查 在这里
        self.Button.clicked.connect(self.login)
        self.do_something_in_time()

    def test_state(self):
        # 所有权限
        url = "http://www.ym94.cn/robot/ALL.txt"
        try:
            mes = requests.get(url=url).text
            mes = str(mes).replace("\n", "").replace(" ", "").replace("\r", "")
            # 如果远程服务器显示0 则该软件不能使用
            if str(mes) == str(0):
                QMessageBox.information(self, "提示！", "由于特殊原因，该软件停止使用！相关详情联系作者QQ：1021644865",
                                        QMessageBox.Yes | QMessageBox.No)
                # 直接杀死程序
                os._exit(0)
            pass
        except:
            pass

    def test_network(self):
        # 网络自检
        try:
            # 定时自检
            self.timer1 = QTimer(self)
            # 绑定函数
            self.timer1.timeout.connect(self.do_something_in_time)
            self.timer1.start(10000)

            # 抢课定时
            self.timer2 = QTimer(self)
            self.timer2.timeout.connect(self.test_qk)
            self.timer2.start(1000)
        except Exception as e:
            self.logger.write(traceback.format_exc())
        pass

    def do_something_in_time(self):
        # 所有的自检程序 10s
        self.test_baidu()
        self.test_hnuc()
        self.test_state()

    def test_baidu(self):
        # 自检百度
        try:
            url = "https://www.baidu.com/"
            stat = requests.get(url=url, timeout=3000)
            # print(stat)
            if str(stat.status_code) != "200":
                # print("百度状态：" + str(stat.status_code))
                QMessageBox.information(self, "提示！", "请先连接网络！", QMessageBox.Yes | QMessageBox.No)
                self.baiduLable.setText("<html><head/><body><p><span style=\" color:#ff0000;\">异常</span>"
                                        "</p></body></html>")
                return False
            else:
                self.baiduLable.setText("<html><head/><body><p><span style=\" color:#00aa00;\">正常"
                                        "</span></p></body></html>")
                return True
        except:
            self.logger.write("error341:" + str(traceback.format_exc()))
            self.baiduLable.setText("<html><head/><body><p><span style=\" color:#ff0000;\">异常</span>"
                                    "</p></body></html>")
            return False

    def test_hnuc(self):
        # 自检教务系统
        try:
            url = "http://jwgl.hutb.edu.cn/jsxsd/"
            stat = requests.get(url=url, timeout=3000)
            # print(stat)
            # print("教务系统状态：" + str(stat.status_code))
            if str(stat.status_code) != "200":
                QMessageBox.information(self, "提示！", "教务系统出现故障！", QMessageBox.Yes | QMessageBox.No)
                self.hnucLable.setText("<html><head/><body><p><span style=\" color:#ff0000;\">异常</span>"
                                       "</p></body></html>")
                return False
            else:
                self.hnucLable.setText("<html><head/><body><p><span style=\" color:#00aa00;\">正常"
                                       "</span></p></body></html>")
                return True
            # <html><head/><body><p><span style=" color:#00aa00;">NULL</span></p></body></html>
        except:
            self.logger.write("error362" + str(traceback.format_exc()))
            self.hnucLable.setText("<html><head/><body><p><span style=\" color:#ff0000;\">异常</span>"
                                   "</p></body></html>")
            return False

    def test_qk(self):
        # 定时抢课
        testFlag = False
        try:
            # 如果没有登录或者队伍没有课程

            if (not self.flag):
                return
            if self.USER.is_ready():
                # 如果检查能抢课，持续发送数据包
                num = 0
                while num < self.count:
                    QKID = self.userClassState[num].objectName()
                    # 获得stat
                    # print("获得唯一标识符" + str(QKID))
                    # 根据唯一标识找到ID

                    # 如果已经抢到了，跳过
                    if self.SUCCESS[str(QKID)]:
                        num += 1
                        continue
                    # 获得输入的ID
                    ID = self.QKall[str(QKID)]
                    # print("ID为："+str(ID))
                    msg = self.USER.post_Class(id=ID)
                    showMsg = self.userClassState[num].text()
                    print(msg)
                    if msg["code"] == 100:
                        # print("出现异常")
                        # 恢复一
                        if self.USER.get_qk_page2():
                            continue
                        showMsg = "<html><head/><body><p><span style=\" color:#ff0000;\">出现异常</span>" \
                                  "</p></body></html>"
                        testFlag = True
                    elif msg["code"] == 200:
                        showMsg = "<html><head/><body><p><span style=\" color:#00aa00;\">抢课成功！</span>" \
                                  "</p></body></html>"
                        self.SUCCESS[str(QKID)] = True
                        # mes = "<html><head/><body><p align=\"center\">抢到课程！</p></body></html>"
                    else:
                        # print(msg)
                        pass
                    """
                        根据拿到的ID 去请求
                        然后根据结果反馈信息，如果结果是抢到了，标识 SECCUSS，修改显示情况
                        查找所有的课程，一次性监控所有的课程
                    """
                    # 修改显示信息
                    self.userClassState[num].setText(showMsg)
                    num += 1
                for j in self.QKNAME:
                    name = j
                    stat = self.USER.findClassByAll(kcName=str(name))
                    # print(stat)
                    if stat['code'] != 200:
                        continue
                    else:
                        for k in stat["jxid"]:
                            # print(k, end="  ")
                            stat = self.USER.post_Class(id=k)
                            if stat["code"] == 200:
                                QMessageBox.information(self, "提示！", str(j) + "抢课成功！", QMessageBox.Yes | QMessageBox.No)
                                self.QKNAME.remove(j)
                            # print(stat)
                for j in self.QKTYPE:
                    name = j
                    stat = self.USER.findClassByTYPE(type=str(name))
                    if stat['code'] != 200:
                        continue
                    else:
                        for k in stat["jxid"]:
                            # print(k, end="  ")
                            stat = self.USER.post_Class(id=k)
                            # print(stat)
                            if stat["code"] == 200:
                                self.QKTYPE.remove(j)
                                QMessageBox.information(self, "提示！", "类型：" + str(j) + "抢课成功！",
                                                        QMessageBox.Yes | QMessageBox.No)

                if testFlag:
                    if self.USER.login_in():
                        pass
            else:
                # 如果不能抢课,状态全部变成红色
                if self.count > 0:
                    num = 0
                    while num < self.count:
                        text = self.userClassState[num].text()
                        stat = re.findall(r"\">.*</p>", str(text))[0]
                        stat = str(stat).replace("\">", "").replace("</p>", "")
                        # 标签变成红色
                        stat = "<html><head/><body><p align=\"center\" style=\" color:#ff0000;\">抢课未开始</p></body></html>"
                        self.userClassState[num].setText(stat)
                        num += 1
                else:
                    pass
        except:
            self.logger.write("Main518：error~!")
            self.logger.write(traceback.format_exc())

    def login(self):

        # 登录
        user = self.userLineEdit.text()
        user = str(user).replace(" ", "").replace("\r", "").replace("\t", "").replace("\n", "")
        # 密码
        password = self.passwordLineEdit.text()
        password = str(password).replace(" ", "").replace("\r", "").replace("\t", "").replace("\n", "")

        # 备注
        nick = self.nickLineEdit.text()
        nick = str(nick).replace(" ", "").replace("\r", "").replace("\t", "").replace("\n", "")

        # 新增课程的类型
        NewkcType = self.NewkcTypeLineEdit.text()
        NewkcType = str(NewkcType).replace(" ", "").replace("\r", "").replace("\t", "").replace("\n", "")
        # 新增课程的名字
        NewkcName = self.NewkcNameLineEdit.text()
        NewkcName = str(NewkcName).replace(" ", "").replace("\r", "").replace("\t", "").replace("\n", "")
        # 扩容抢课Nmae
        kcName = self.kcNameLineEdit.text()
        kcName = str(kcName).replace(" ", "").replace("\r", "").replace("\t", "").replace("\n", "")
        # 课程的老师
        kcTeacher = self.kcTeacherLineEdit.text()
        kcTeacher = str(kcTeacher).replace(" ", "").replace("\r", "").replace("\t", "").replace("\n", "")
        # 上课的节次
        kcJC = self.kcJCLineEdit.text()
        kcJC = str(kcJC).replace(" ", "").replace("\r", "").replace("\t", "").replace("\n", "")
        # 上课的星期
        kcWeek = self.kcWeekLineEdit.text()
        kcWeek = str(kcWeek).replace(" ", "").replace("\r", "").replace("\t", "").replace("\n", "")
        # nick
        # kcWeek
        # kcJC
        # kcTeacher
        # kcName
        # NewkcName
        # NewkcType

        # 登录了
        if not self.flag:
            try:
                laji = School(user=user, password=password)
            except Exception as e:
                QMessageBox.information(self, "提示！", "登录出现异常！请联系作者", QMessageBox.Yes | QMessageBox.No)
                self.logger.write("error788：登录出现问题" + str(traceback.format_exc()))
                return
            try:
                if laji.login_in():
                    # 返回名字
                    self.USER = laji
                    name = self.USER.name
                    self.logger.write(str(name) + "登录成功~")
                    # 账号和密码不能再修改了
                    self.userLineEdit.setReadOnly(True)
                    self.passwordLineEdit.setReadOnly(True)
                    # 显示用户名字
                    self.notChangeLable1.setText(self.__labe_center("用户：" + str(name)))

                    QMessageBox.information(self, "提示！", "登录成功", QMessageBox.Yes | QMessageBox.No)

                    self.nickLineEdit.setText("")
                    self.kcWeekLineEdit.setText("")
                    self.kcJCLineEdit.setText("")
                    self.kcTeacherLineEdit.setText("")
                    self.kcNameLineEdit.setText("")
                    self.NewkcNameLineEdit.setText("")
                    self.NewkcTypeLineEdit.setText("")
                    # 表示已经登录过了
                    self.flag = True
                    return
                else:
                    QMessageBox.information(self, "提示！", "添加失败，请检查账号、密码是否正确",
                                            QMessageBox.Yes | QMessageBox.No)
                    return
            except Exception as e:
                self.logger.write("error:main-> 1036  " + str(traceback.format_exc()))
                return

        # 添加课程
        if self.flag:
            # 检查输入不能为空
            if self.__isNone(nick):
                QMessageBox.information(self, "提示！", "备注不能为空！", QMessageBox.Yes | QMessageBox.No)
                return
            # nick
            # kcWeek
            # kcJC
            # kcTeacher
            # kcName
            # NewkcName
            # NewkcType

            # 检查是否填了信息
            if (not self.__isNone(NewkcName)):
                # 增加课程名字
                self.USER.get_qk_page2()
                try:
                    # print(NewkcName)
                    msg = self.USER.findClassByAll(kcName=str(NewkcName))
                    if msg["code"] != 200:
                        QMessageBox.information(self, "提示！", "请检查课程名字！", QMessageBox.Yes | QMessageBox.No)
                        return
                    else:
                        self.QKNAME.append(str(NewkcName))
                        QMessageBox.information(self, "提示！", "添加成功！后台自动抢课", QMessageBox.Yes | QMessageBox.No)
                        self.NewkcNameLineEdit.setText("")
                        return
                except:
                    pass
            elif (not self.__isNone(NewkcType)):
                # 增加课程type
                self.USER.get_qk_page2()
                try:
                    msg = self.USER.findClassByTYPE(type=str(NewkcType))
                    if msg["code"] != 200:
                        QMessageBox.information(self, "提示！", "请检查课程类型！", QMessageBox.Yes | QMessageBox.No)
                        return
                    else:
                        self.QKTYPE.append(str(NewkcType))
                        QMessageBox.information(self, "提示！", "添加成功！后台自动抢课", QMessageBox.Yes | QMessageBox.No)
                        self.NewkcTypeLineEdit.setText("")
                        return
                except:

                    self.logger.write(traceback.format_exc())
                pass
            elif (not self.__isNone(kcName) and (not self.__isNone(kcTeacher)) and (not self.__isNone(kcJC)) and (
                    not self.__isNone(kcWeek))):
                if self.USER.get_qk_page2():
                    try:
                        msg = self.USER.findClassByOne(kcName=str(kcName), kcTeacher=str(kcTeacher), kcJC=str(kcJC),
                                                       kcWeek=str(kcWeek))
                        if msg["code"] == 200:
                            jxid = msg["jxid"]
                            self.add_class(jxid=jxid, nick=nick)
                            QMessageBox.information(self, "提示！", str(msg["msg"]), QMessageBox.Yes | QMessageBox.No)
                            self.nickLineEdit.setText("")
                            self.kcWeekLineEdit.setText("")
                            self.kcJCLineEdit.setText("")
                            self.kcTeacherLineEdit.setText("")
                            self.kcNameLineEdit.setText("")
                            self.NewkcNameLineEdit.setText("")
                            self.NewkcTypeLineEdit.setText("")
                        else:
                            QMessageBox.information(self, "提示！", str(msg["msg"]), QMessageBox.Yes | QMessageBox.No)
                    except:
                        self.logger.write(traceback.format_exc())
                else:
                    QMessageBox.information(self, "提示！", "登录或教务系统出现问题！请重新进入", QMessageBox.Yes | QMessageBox.No)
                pass
            else:
                QMessageBox.information(self, "提示！", "请输入完整的扩容的信息！", QMessageBox.Yes | QMessageBox.No)
                return
            return

    def add_class(self, jxid, nick):
        # 抢课ID自增 唯一
        self.QKID += 1
        #  self.QKID 是抢课的唯一标识符号
        _translate = QtCore.QCoreApplication.translate
        try:
            # 获得ID
            # 加入抢课大队
            self.QKall[str(self.QKID)] = str(jxid)
            # 是否成功抢课
            self.SUCCESS[str(self.QKID)] = False

        except Exception as e:
            self.logger.write("error:main-> 1128  添加课程出错！ " + str(traceback.format_exc()))
            return
        try:
            if self.count == 0:
                self.userButton = {}
                self.userAddLable = {}
                self.userClassState = {}
            elif self.count > 7:
                QMessageBox.information(self, "提示！", "单个账号最多抢8门课程", QMessageBox.Yes | QMessageBox.No)
                return
            # 按钮，记得绑定事件
            self.userButton[self.count] = QtWidgets.QPushButton(self.user1Frame)
            self.userButton[self.count].setObjectName("delButton" + str(self.count))
            self.userButton[self.count].setGeometry(QtCore.QRect(510, 90 + self.count * 40, 81, 28))
            self.userButton[self.count].setText(_translate("MainWindow", "删除"))
            self.userButton[self.count].clicked.connect(self.delt_class)
            # 显示的状态,添加唯一ID，OBJname
            self.userClassState[self.count] = QtWidgets.QLabel(self.user1Frame)
            self.userClassState[self.count].setObjectName(str(self.QKID))  # 唯一ID
            self.userClassState[self.count].setGeometry(QtCore.QRect(270, 90 + self.count * 40, 101, 20))
            self.userClassState[self.count].setText(_translate("MainWindow", self.__labe_center("抢课中...")))
            # 显示的课程
            self.userAddLable[self.count] = QtWidgets.QLabel(self.user1Frame)
            self.userAddLable[self.count].setObjectName("loadingLable" + str(self.count))
            self.userAddLable[self.count].setGeometry(QtCore.QRect(60, 90 + self.count * 40, 211, 20))
            self.userAddLable[self.count].setText(_translate("MainWindow", "" + str(nick)))
        except:
            self.logger.write("error 1143:UI添加出错！" + str(traceback.format_exc()))
        try:
            # 记得显示出来
            self.userButton[self.count].show()
            self.userAddLable[self.count].show()
            self.userClassState[self.count].show()
            self.count += 1
        except:
            self.logger.write("error 1152:" + str(traceback.format_exc()))
        pass

    def __labe_center(self, mes):
        return "<html><head/><body><p align=\"center\">" + str(mes) + "</p></body></html>"

    def delt_class(self):
        # sender 直接可以定位到发送信号的控件
        try:
            sender = self.sender()
            # 提取需要删除的编号
            count = str(sender.objectName()).replace("delButton", "")
            count = int(count)
            num = count
            self.userButton[num].deleteLater()
            self.userAddLable[num].deleteLater()
            self.userClassState[num].deleteLater()
            # 由于是类似指针，所以最后用一个不需要操作,指针类似，最后一个不要清空
            while num < self.count - 1:
                # 重新设定button
                self.userButton[num] = self.userButton[num + 1]
                self.userButton[num].setObjectName("delButton" + str(num))
                self.userButton[num].setGeometry(QtCore.QRect(510, 90 + num * 40, 81, 28))
                # 状态
                self.userClassState[num] = self.userClassState[num + 1]
                # self.userClassState[num].setObjectName("state" + str(num))
                self.userClassState[num].setGeometry(QtCore.QRect(270, 90 + num * 40, 101, 20))

                # 课程
                self.userAddLable[num] = self.userAddLable[num + 1]
                self.userAddLable[num].setObjectName("loadingLable" + str(num))
                self.userAddLable[num].setGeometry(QtCore.QRect(60, 90 + num * 40, 211, 20))
                num += 1

            self.count -= 1
        except:
            self.logger.write("error 1188(删除UI出错！):" + str(traceback.format_exc()))

    """
    下面的都是基本设置
    """

    def center(self, MainWindow):
        # 自动把屏幕放在正中间
        # 获得窗口
        qr = MainWindow.frameGeometry()
        # 获得屏幕中心点
        cp = QDesktopWidget().availableGeometry().center()
        # 显示到屏幕中心
        qr.moveCenter(cp)
        MainWindow.move(qr.topLeft())

    def __isNone(self, mes):
        try:
            if str(mes) == None or len(str(mes)) < 1 or str(mes) == "":
                return True
            return False
        except Exception as e:
            self.logger.write("error 1210:判断为空error！):" + str(traceback.format_exc()))


#
# if __name__ == '__main__':
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
